<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>circle packing</title>
	<!-- 引入echarts库文件 -->
    <script src="../static_js/echarts.min.js"></script>
    <!-- 引入jquery库文件 -->
    <script src="../static_js/jquery.js"></script>


</head>
<body>
	<!-- 定义图表现实区域 -->
    <div id="main" style="width:1380px; height: 620px"></div>
	<script type="text/javascript">
		<!-- 初始化echarts对象 -->
        var chartDom = document.getElementById('main');
        var myChart = echarts.init(chartDom);
        var option;

        $.when(
            // $.get('files/option-view.json'),
            $.get('../community_fenji/files/data_demo2.json'),
            $.getScript('https://cdn.jsdelivr.net/npm/d3-hierarchy@2.0.0/dist/d3-hierarchy.min.js')
        ).done(function (res) {
            run(res[0]);
            // run(res);
        });

        function run(rawData) {

            var dataWrap = prepareData(rawData);

            initChart(dataWrap.seriesData, dataWrap.maxDepth);
        }

        function prepareData(rawData) {
            var seriesData = [];
            var maxDepth = 0;

            function convert(source, basePath, depth) {
                if (source == null) {
                    return;
                }
                if (maxDepth > 5) {
                    return;
                }
                maxDepth = Math.max(depth, maxDepth);

                seriesData.push({
                    id: basePath,
                    value: source.$count,
                    depth: depth,
                    index: seriesData.length
                });

                for (var key in source) {
                    if (source.hasOwnProperty(key) && !key.match(/^\$/)) {
                        //这一行展示数据目前不能随意乱动
                        var path = basePath + '.' + key;
                        convert(source[key], path, depth + 1);

                    }
                }
            }

            // convert(rawData, 'option', 0);
            convert(rawData, '郑州市', 0);

            return {
                seriesData: seriesData,
                maxDepth: maxDepth
            };
        }

        function initChart(seriesData, maxDepth) {
            var displayRoot = stratify();

            function stratify() {
                return d3.stratify()
                    .parentId(function (d) {
                        return d.id.substring(0, d.id.lastIndexOf('.'));
                    })(
                        seriesData
                    )
                    .sum(function (d) {
                        return d.value || 0;
                    })
                    .sort(function (a, b) {
                        return b.value - a.value;
                    });
            }

            function overallLayout(params, api) {
                var context = params.context;
                d3.pack()
                    .size([api.getWidth() - 2, api.getHeight() - 2])
                    .padding(3)(displayRoot);

                context.nodes = {};
                displayRoot.descendants().forEach(function (node, index) {
                    context.nodes[node.id] = node;
                });
            }

            function renderItem(params, api) {
                var context = params.context;

                // Only do that layout once in each time `setOption` called.
                if (!context.layout) {
                    context.layout = true;
                    overallLayout(params, api);
                }

                var nodePath = api.value('id');
                var node = context.nodes[nodePath];

                if (!node) {
                    // Reder nothing.
                    return;
                }

                var isLeaf = !node.children || !node.children.length;

                var focus = new Uint32Array(node.descendants().map(function (node) {
                    return node.data.index;
                }));

                var nodeName = isLeaf
                    ? nodePath.slice(nodePath.lastIndexOf('.') + 1).split(/(?=[A-Z][^A-Z])/g).join('\n')
                    : '';

                var z2 = api.value('depth') * 2;

                return {
                    type: 'circle',
                    focus: focus,
                    shape: {
                        cx: node.x,
                        cy: node.y,
                        r: node.r
                    },
                    transition: ['shape'],
                    z2: z2,
                    textContent: {
                        type: 'text',
                        style: {
                            // transition: isLeaf ? 'fontSize' : null,
                            text: nodeName,
                            fontFamily: 'Arial',
                            width: node.r * 1.3,
                            overflow: 'truncate',
                            fontSize: node.r / 3
                        },
                        emphasis: {
                            style: {
                                overflow: null,
                                fontSize: Math.max(node.r / 3, 12)
                            }
                        }
                    },
                    textConfig: {
                        position: 'inside'
                    },
                    style: {
                        fill: api.visual('color')
                    },
                    emphasis: {
                        style: {
                            fontFamily: 'Arial',
                            fontSize: 12,
                            shadowBlur: 20,
                            shadowOffsetX: 3,
                            shadowOffsetY: 5,
                            shadowColor: 'rgba(0,0,0,0.3)'
                        }
                    }
                };
            }

            var option = {
                dataset: {
                    source: seriesData
                },
                tooltip: {},
                visualMap: {
                    show: false,
                    min: 0,
                    max: maxDepth,
                    dimension: 'depth',
                    inRange: {
                        color: [
                            '#006edd',
                            // '#e0ffff',//白色
                            // '#1d953f',//绿色
                            // '#ff8c00',//橘色
                            '#afeeee',
                        ]
                    }
                },
                hoverLayerThreshold: Infinity,
                series: {
                    type: 'custom',
                    renderItem: renderItem,
                    progressive: 0,
                    coordinateSystem: 'none',
                    encode: {
                        tooltip: 'value',
                        itemName: 'id'
                    }
                }
            };

            myChart.setOption(option);
            // 自带有点击事件的实现
            myChart.on('click', { seriesIndex: 0 }, function (params) {
                drillDown(params.data.id);
            });

            function drillDown(targetNodeId) {
                displayRoot = stratify();
                if (targetNodeId != null) {
                    displayRoot = displayRoot.descendants().find(function (node) {
                        return node.data.id === targetNodeId;
                    });
                }
                // else {
                //     window.location.href = 'index.html'
                // }
                // A trick to prevent d3-hierarchy from visiting parents in this algorithm.
                displayRoot.parent = null;

                myChart.setOption({
                    dataset: {
                        source: seriesData
                    }
                });
            }

            // 点击非图表元素效果
            // Reset: click on the blank area.
            myChart.getZr().on('click', function (event) {
                if (!event.target) {
                    drillDown();
                }
            });
        }

        option && myChart.setOption(option);

        // 跳转事件的实现
        myChart.on('click', function(params){
            // alert(params.name)
            if (params.componentType === 'series'){
                if(params.seriesType === 'custom'){
                    // alert(params.data.value)
                    // alert(params.data.id) //等价于下一句
                    // alert(params.name)
                    //成功定位最后一层，然后进行跳转
                    if(params.data.value === 1000){
                        alert(params.data.id)
                        window.location.href = 'index-test.html'
                    }

                }
            }

        });

		
	</script>
</body>
</html>